interface RouterParams {
	path: string
	query?: { [key: string]: any }
}
/**
 * @name 校验路由过滤参数
 */
function filterParams(route: RouterParams | string) {
	// 传入纯路由字符串初始化对象
	if (typeof route == 'string') {
		route = {
			path: route,
			query: {}
		}
	}
	// 容错处理，未传斜杠自动补全
	if (route.path[0] !== '/') {
		route.path = `/${route.path}`
	}
	// 循环过滤参数，防止报错
	for (const i in route.query) {
		if (route.query[i] === null || route.query[i] == undefined) {
			delete route.query[i]
		}
	}
	return route
}
/**
 * @name obj转params字符串参数
 * @example {a:1, b:2} => a=1&b=2
 */
function objParseParam(obj: RouterParams['query']) {
	let paramsStr = ''
	if (obj instanceof Array) return paramsStr
	if (!(obj instanceof Object)) return paramsStr
	for (const key in obj) {
		paramsStr += `${key}=${obj[key]}&`
	}
	return paramsStr.substring(0, paramsStr.length - 1)
}
/**
 * @name obj转路由地址带参数
 * @example {a:1, b:2} => /pages/index/index?a=1&b=2
 */
function objParseUrlAndParam(route: RouterParams) {
	let paramsStr = ''
	let url = route.path || '/'
	if (route.query instanceof Array) return url
	if (!(route.query instanceof Object)) return url
	paramsStr = objParseParam(route.query)
	if (paramsStr) url += '?'
	url += paramsStr
	return url
}

const router = {
	/**
	 * @name 保留当前页面，跳转到应用内的某个页面
	 */
	push(route: RouterParams | string) {
		route = filterParams(route)
		uni.navigateTo({
			url: objParseUrlAndParam(route),
			fail: (error: any) => {
				console.error(error)
			}
		})
	},
	/**
	 * @name 跳转到tabBar页面，并关闭其他所有非tabBar页面
	 */
	pushTab(route: RouterParams | string) {
		route = filterParams(route)
		uni.switchTab({
			url: objParseUrlAndParam(route),
			fail: (error: any) => {
				console.error(error)
			}
		})
	},
	/**
	 * @name 关闭当前页面，跳转到应用内的某个页面
	 */
	replace(route: RouterParams | string) {
		route = filterParams(route)
		uni.redirectTo({
			url: objParseUrlAndParam(route),
			fail: (error: any) => {
				console.error(error)
			}
		})
	},
	/**
	 * @name 关闭所有页面，打开到应用内的某个页面
	 */
	replaceAll(route: RouterParams | string) {
		route = filterParams(route)
		uni.reLaunch({
			url: objParseUrlAndParam(route),
			fail: (error: any) => {
				console.error(error)
			}
		})
	},
	/**
	 * @name 关闭当前页面，返回上一页面或多级页面
	 */
	back(delta = 1) {
		uni.navigateBack({
			delta,
			fail: (error: any) => {
				console.error(error)
			}
		})
	}
}

const U = {
	/**
	 * @name 格式化W单位
	 */
	formatNumber(v: number) {
		if (v > 9999) {
			return (v / 10000).toFixed(2) + 'w'
		}
		return v
	}
}
export default {
	...router,
	...U
}
